<template>
  <div id="addQuestionView">
    <a-form :model="form" style="width: 90%">
      <a-form-item field="title" label="标题">
        <a-input v-model="form.title" placeholder="请输入标题" />
      </a-form-item>
      <a-form-item field="tags" label="标签">
        <a-input-tag v-model="form.tags" placeholder="请输入标签" allow-clear />
      </a-form-item>
      <a-form-item field="content" label="题目内容">
        <MdEditor :value="form.content" :handle-change="onContentValueChange" />
      </a-form-item>
      <a-form-item field="answer" label="答案">
        <MdEditor :value="form.answer" :handle-change="onAnswerValueChange" />
      </a-form-item>
      <a-form-item label="判题配置" :content-flex="false" :merge-props="false">
        <a-space direction="vertical" style="min-width: 480px">
          <a-form-item field="judgeConfig.memoryLimit" label="内存限制">
            <a-input-number
              v-model="form.judgeConfig.memoryLimit"
              placeholder="请输入内存限制(kb)"
              mode="button"
              size="large"
              min="0"
            />
          </a-form-item>
          <a-form-item field="judgeConfig.timeLimit" label="时间限制">
            <a-input-number
              v-model="form.judgeConfig.timeLimit"
              placeholder="请输入时间限制(ms)"
              mode="button"
              size="large"
              min="0"
            />
          </a-form-item>
          <a-form-item field="judgeConfig.stackLimit" label="堆栈限制">
            <a-input-number
              v-model="form.judgeConfig.stackLimit"
              placeholder="请输入堆栈限制(kb)"
              mode="button"
              size="large"
              min="0"
            />
          </a-form-item>
        </a-space>
      </a-form-item>
      <a-form-item label="测试用例" :content-flex="false" :merge-props="false">
        <a-form-item
          v-for="(judgeCaseItem, index) of form.judgeCases"
          :key="index"
          no-style
        >
          <a-space direction="vertical" style="min-width: 800px">
            <a-form-item
              :field="`form.judgeCases[${index}].input`"
              :label="`输入用例-${index}`"
              :key="index"
            >
              <a-input v-model="judgeCaseItem.input" />
            </a-form-item>
            <a-form-item
              :field="`form.judgeCases[${index}].input`"
              :label="`输出用例-${index}`"
              :key="index"
            >
              <a-input v-model="judgeCaseItem.output" />
            </a-form-item>
            <a-button @click="handleDelete(index)" status="danger"
              >删除
            </a-button>
          </a-space>
        </a-form-item>
        <div>
          <a-button
            @click="handleAdd"
            type="outline"
            status="success"
            style="margin-top: 26px"
            >新增测试用例
          </a-button>
        </div>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" style="min-width: 180px" @click="handleSubmit"
          >提交
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, toRaw } from "vue";
import MdEditor from "@/components/MdEditor.vue";
import { QuestionControllerService } from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRoute, useRouter } from "vue-router";

const form = reactive({
  answer: "",
  content: "",
  judgeCases: [
    {
      input: "",
      output: "",
    },
  ],
  judgeConfig: {
    memoryLimit: 0,
    stackLimit: 0,
    timeLimit: 0,
  },
  tags: [],
  title: "",
});
const route = useRoute();
const router = useRouter();
//根据路径判断是否为修改题目
const updatePage = route.path.includes("update");
const loadData = async () => {
  const id = route.query.id;
  if (!id) {
    return;
  } else {
    const res = await QuestionControllerService.getQuestionByIdUsingGet(
      id as any
    );
    if (res.code === 0) {
      console.log(res.data);

      // 解析 JSON 字符串，并提供默认值
      const parsedTags = JSON.parse(res.data?.tags as string) || [];
      const parsedJudgeConfig =
        JSON.parse(res.data?.judgeConfig as string) || {};
      const parsedJudgeCases = JSON.parse(res.data?.judgeCases as string) || [];

      // 将解析后的值赋给 form
      Object.assign(form, {
        ...res.data,
        tags: parsedTags,
        judgeConfig: parsedJudgeConfig,
        judgeCases: parsedJudgeCases,
      });
    } else {
      message.error("数据获取失败" + res.message);
    }
  }
};

onMounted(() => {
  loadData();
});
const handleAdd = () => {
  form.judgeCases.push({
    input: "",
    output: "",
  });
};
const handleDelete = (index: number) => {
  form.judgeCases.splice(index, 1);
};
const handleSubmit = async () => {
  //console.log(toRaw(form));
  //判断是更新请求还添加请求
  if (updatePage) {
    //向后端发送修改题目的请求
    const res = await QuestionControllerService.updateQuestionUsingPost(form);
    if (res.code === 0) {
      message.success("题目修改成功");
      //回到修改页面
      router.back();
    } else {
      message.error("题目修改失败" + res.message);
    }
  } else {
    //向后端发送添加题目的请求
    const res = await QuestionControllerService.addQuestionUsingPost(form);
    if (res.code === 0) {
      message.success("题目添加成功");
    } else {
      message.error("题目添加失败" + res.message);
    }
  }
};

const onAnswerValueChange = (v: string) => {
  form.answer = v;
};

const onContentValueChange = (v: string) => {
  form.content = v;
};
</script>

<style scoped>
#addQuestionView {
}
</style>
